package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import common.FilePathHelper;
import common.PropertyHelper;
import common.WebServiceInfoRequestor;

/**
 * Servlet implementation class PropertyServlet
 */
public class PropertyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private static String[] propertyNames = new String[3];
    static {
    	propertyNames[0] = "oldwebserviceurl";
    	propertyNames[1] = "bbanwebserviceurl";
    	propertyNames[2] = "ibanwebserviceurl";
    }
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PropertyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		if(action!=null&&action.equals("write")){
			String[] propVals = new String[3];
			propVals[0] = request.getParameter("oldwebserviceurl");
			propVals[1] = request.getParameter("bbanwebserviceurl");
			propVals[2] = request.getParameter("ibanwebserviceurl");
			
			PrintWriter out = response.getWriter();
			if(PropertyHelper.writeProperties(FilePathHelper.getPropFilePath(), propertyNames, propVals, 3)) {
				out.print("success");
				
				//Update web service url property in memory
				WebServiceInfoRequestor.updateWebServiceUrl(URLDecoder.decode(propVals[0]), URLDecoder.decode(propVals[1]), URLDecoder.decode(propVals[2]));
			}
			else {
				out.print("failed");
			}
			
			out.flush();
			out.close();
		}else{
			String[] propertyVals = new String[3];
			PropertyHelper.readProperties(FilePathHelper.getPropFilePath(), propertyNames, propertyVals, 3);
			String getParam = "?";
			for(int i=0;i<3;i++) {
				getParam += propertyNames[i] + "=" + propertyVals[i] + "&";
			}
			RequestDispatcher dispatcher = request.getRequestDispatcher("admin.jsp"+getParam);
			dispatcher.forward(request, response);
		}
	}
	

}
